<template>
  <div class="app-container">
    <el-tabs
      v-model="tabNum"
      @tab-click="handleClick"
      style="padding: 10px 0 10px 10px; background: #fff"
    >
      <el-tab-pane label="风险预警消息" name="1">
        <avue-crud
          :option="option"
          ref="crud"
          :data="data"
          :table-loading="loading"
          :page.sync="page"
          @on-load="onLoad"
          @current-change="currentChange"
          @search-change="searchChange"
          @search-reset="resetChange"
        >
          <template slot-scope="{ type, size, row }" slot="menu">
            <el-button :size="size" :type="type" @click="celCustomer(row)"
              >查看</el-button
            >
          </template>
          <template slot="menuLeft" slot-scope="{ row }">
            <el-button type="primary" size="small" @click="handelAllRead(row)"
              >全部已读</el-button
            >
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane label="预警消息设置" name="2">
        <div class="formBox">
          <div style="width: 100%">
            <el-form :model="infoSetingData" label-width="110px">
              <!-- <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item label="风控报告下载提醒:">
                  <el-select
                    v-model="infoSetingData.one"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item, index) in signInfoOption"
                      :label="item.label"
                      :value="item.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item label="企业风险消息提醒:">
                  <el-select
                    v-model="infoSetingData.two"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item, index) in signInfoOption"
                      :label="item.label"
                      :value="item.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->
              <el-row :gutter="20" v-if="infoSetingData.two == 'Y'">
                <p class="spanClass">消息内容设置</p>
                <el-col :span="18">
                  <el-form-item
                    v-for="item in riskList"
                    :label="item.fxdlName"
                    :key="item.id"
                  >
                    <el-checkbox-group
                      v-model="item.selectArr"
                      @change="(val) => checkBoxEven(val, item)"
                    >
                      <el-checkbox label="高风险" name="high"></el-checkbox>
                      <el-checkbox label="中风险" name="medium"></el-checkbox>
                      <el-checkbox label="低风险" name="low"></el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div style="width: 100%">
            <el-form :model="infoSetingData" label-width="110px">
              <el-row :gutter="20">
                <p class="spanClass">推送方式设置</p>
                <el-col :span="18">
                  <el-form-item label="平台推送:">
                    <el-switch v-model="infoSetingData.delivery"></el-switch>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="邮件推送:">
                    <el-switch v-model="infoSetingData.deliveryOne"></el-switch>
                    <el-input
                      v-model="infoSetingData.email"
                      style="width: 40%; margin-left: 20px"
                      :disabled="!infoSetingData.deliveryOne"
                      @input="emailChang"
                    ></el-input>
                    <span v-if="!validEmail" style="color: red"
                      >请输入正确的邮件格式</span
                    >
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="短信推送:">
                    <el-switch
                      v-model="infoSetingData.deliveryTwo"
                      disabled
                    ></el-switch>
                    <el-input
                      v-model="infoSetingData.phoneNum"
                      style="width: 40%; margin-left: 20px"
                      :disabled="!infoSetingData.deliveryTwo"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="18">
                  <p style="font-size: 12px; margin-left: 50px">
                    说明：至少选择一种推送方式,默认推送方式为平台推送
                  </p>
                </el-col>
                <el-col :span="18" :offset="2" style="margin-top: 40px">
                  <el-button type="primary" @click="saveBtn">保 存</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      title="消息详情"
      class="avue-dialog"
      center
      :visible.sync="openCel"
      width="40%"
    >
      <div class="contBox">
        <el-form :model="form" label-position="right" label-width="100px">
          <el-form-item label="消息类型:">
            <span>风险预警消息</span>
          </el-form-item>
          <el-form-item label="消息推送时间:">
            <span>{{ form.createTime }}</span>
          </el-form-item>
          <el-form-item label="企业名称:">
            <span>{{ form.qymc }}</span>
          </el-form-item>
          <el-form-item label="风险类型:">
            <span>{{ form.fxdl }}</span>
          </el-form-item>
          <el-form-item label="风险名称:">
            <span>{{ form.yjxl }}</span>
          </el-form-item>
          <el-form-item label="风险等级:">
            <span>{{ form.yjdj }}</span>
          </el-form-item>
          <el-form-item label="风险发生时间:">
            <span>{{
              form.yjTime ? form.yjTime.slice(0, 11) : form.yjTime
            }}</span>
          </el-form-item>
          <el-form-item label="风险详情:">
            <span>{{ form.yjxq }}</span>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="openCel = false">关闭</el-button>
          <el-button
            @click="handleCheck"
            :disabled="form.readFlagStr == '已读'"
            type="primary"
            >已读</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import {
  getPushHistory,
  jrfkFxyjPus,
  updateUserHistoryReaded,
  getSettingInfo,
  saveSettingInfo,
  getWebSocketInfo,
} from "@/api/manager.js";
import { getUser } from "@/api/portay";
export default {
  components: {},
  data() {
    return {
      tabNum: "1",
      loading: false,
      form: { oneNam: "风险预警" },
      bankOptions: [],
      searchList: {},
      openCel: false,
      /* 分页 */
      page: {
        pageSize: 10,
        pageSizes: [10, 20, 30, 40, 50, 100],
        pagerCount: 5,
        layout: "total, sizes, prev, pager, next, jumper",
        currentPage: 1,
        total: 0,
        background: false,
      },
      data: [],
      option: {
        headerAlign: "center",
        align: "center",
        border: true,
        index: true,
        indexLabel: "序号",
        indexWidth: 100,
        card: true,
        defaultExpandAll: true,
        dialogDrag: false,
        labelWidth: 135,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        searchBtn: true,
        searchLabelWidth: "10%",
        searchSpan: 8,
        searchShowBtn: false,
        selection: false,
        menuWidth: 150,
        searchMenuSpan: 4,
        column: [
          {
            label: "企业名称",
            prop: "qymc",
            display: false,
          },
          {
            label: "风险类型",
            prop: "fxdl",
            display: false,
          },
          {
            label: "风险名称",
            prop: "yjxl",
            display: false,
          },
          {
            label: "状态",
            prop: "readFlagStr",
            display: false,
            search: false,
            type: "select",
          },
          {
            label: "消息推送时间",
            prop: "createTime",
            display: false,
          },
          {
            label: "时间",
            prop: "daterange",
            type: "daterange",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd",
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            display: false,
            search: true,
            searchRange: true,
            hide: true,
          },
        ],
      },
      //消息设置
      signInfoOption: [
        {
          label: "接收消息提醒",
          value: "Y",
        },
        {
          label: "不接收",
          value: "N",
        },
      ],
      infoSetingData: {
        one: "",
        two: "",
        three: ["高风险", "中风险"],
        delivery: undefined,
        deliveryOne: undefined,
        deliveryTwo: undefined,
        email: "",
        phoneNum: "",
      },
      //小红点
      isLabelClass: true,
      isLabelClassTwo: true,
      riskList: [],
      paramsObj: {},
      newPushphoneNum: "",
      newPushemail: "",
      validEmail: true,
    };
  },
  filters: {},
  watch: {},
  computed: {
    ...mapGetters(["token"]),
    phoneRegex() {
      return /^1[3456789]\d{9}$/;
    },
    emailRegex() {
      //return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
      //return /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      return /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/;
    },
  },
  created() {
    this.getDict();
    this.getDictTwo();
    this.getDictTree();
    this.tabNum = this.$route.query.type || "1";
    this.getUserinfo();
  },
  methods: {
    //邮箱
    emailChang(val) {
      if (this.emailRegex.test(val)) {
        this.validEmail = true;
      } else {
        this.validEmail = false;
      }
    },
    ...mapActions(["getWebSocketDataList", "websocketonmessage"]),
    //多选事件
    checkBoxEven(item, val) {
      console.log(item, val);
      this.$forceUpdate();
    },
    //消息设置确定按钮
    saveBtn() {
      let { one, two, delivery, deliveryOne, deliveryTwo, phoneNum, email } =
        this.infoSetingData;
      this.paramsObj.fkbgAlarm = one;
      this.paramsObj.qyfxAlarm = two;
      this.paramsObj.platformPush = delivery == true ? "Y" : "N";
      this.paramsObj.emailPush = deliveryOne == true ? "Y" : "N";
      this.paramsObj.messagePush = deliveryTwo == true ? "Y" : "N";
      this.paramsObj.email = email;
      this.paramsObj.message = phoneNum;
      console.log(this.paramsObj.list);
      this.paramsObj.list.forEach((item) => {
        console.log(item.selectArr);
        item.high = "N";
        item.medium = "N";
        item.low = "N";
        item.selectArr.forEach((newInde) => {
          if (newInde == "高风险") {
            item.high = "Y";
          } else if (newInde == "中风险") {
            item.medium = "Y";
          } else if (newInde == "低风险") {
            item.low = "Y";
          }
        });
      });
      let params = Object.assign(this.paramsObj);
      saveSettingInfo(params).then((res) => {
        console.log(res);
        if (res.status) {
          this.$message({
            type: "success",
            message: "设置成功",
          });
          this.getSettingInfo();
        } else {
          this.$message({
            type: "error",
            message: "设置失败",
          });
        }
      });
    },
    async getDictTwo() {
      const dataSQQD = await this.$store.dispatch("asyncApi/getDict", {
        code: "HXFXDL",
      });
    },
    async getDictTree() {
      const yjdjData = await this.$store.dispatch("asyncApi/getDict", {
        code: "YJDJ",
      });
    },
    //获取用户信息
    getUserinfo() {
      let userId = localStorage.getItem("username");
      getUser({ userId }).then((res) => {
        if (res.status) {
          this.newPushemail = res.data ? res.data.userEmail : "";
          this.newPushphoneNum = res.data ? res.data.userPhone : "";
        }
      });
    },
    //获取消息设置内容
    getSettingInfo() {
      getSettingInfo().then((res) => {
        if (res.status) {
          this.paramsObj = res.data;
          res.data.list.forEach((item) => {
            item.selectArr = [];
            if (item.high == "Y") {
              item.selectArr.push("高风险");
            }
            if (item.medium == "Y") {
              item.selectArr.push("中风险");
            }
            if (item.low == "Y") {
              item.selectArr.push("低风险");
            }
          });
          this.infoSetingData.one = res.data.fkbgAlarm;
          this.infoSetingData.two = res.data.qyfxAlarm;
          this.infoSetingData.delivery =
            res.data.platformPush === "Y" ? true : false;
          this.infoSetingData.deliveryOne =
            res.data.emailPush === "Y" ? true : false;
          this.infoSetingData.deliveryTwo =
            res.data.messagePush === "Y" ? true : false;
          this.infoSetingData.email =
            res.data.email !== null ? res.data.email : this.newPushemail;
          this.infoSetingData.phoneNum =
            res.data.message !== null ? res.data.message : this.newPushphoneNum;
          this.riskList = res.data.list;
        }
      });
    },
    //全部已读
    handelAllRead() {
      updateUserHistoryReaded().then((res) => {
        if (res.status) {
          this.onLoad();
          this.getWebSocketDataList();
          this.initWebSocket();
          this.isLabelClass = !this.isLabelClass;
          this.$message({
            message: `${res.msg}`,
            type: "success",
          });
        }
      });
    },
    handleClick(e) {
      if (e.name == "1") {
        this.onLoad();
      } else {
        this.getSettingInfo();
      }
    },
    async getDict() {
      const dataSQQD = await this.$store.dispatch("asyncApi/getDict", {
        code: "SQQD",
      });
      this.bankOptions = dataSQQD;
      this.option.column[3].dicData = dataSQQD;
    },
    onLoad(page, params = {}) {
      let searchList = this.searchList;
      Object.assign(params, {
        ...searchList,
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
      });
      this.loading = true;
      getPushHistory(params).then((data) => {
        if (data.status) {
          this.loading = false;
          this.data = data.data.records;
          this.page.total = data.data.total;
        }
      });
    },
    /* 清空 */
    resetChange(params) {
      params.daterange = [];
      this.page.currentPage = 1;
      this.page.pageSize = 10;
      this.searchList = {};
      this.onLoad();
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done();
      this.page.currentPage = 1;
      this.page.pageSize = 10;
      if (params.daterange) {
        params.startTime = params.daterange[0];
        params.endTime = params.daterange[1];
      }
      params.daterange = [];
      this.searchList = {
        ...params,
      };
      this.onLoad();
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    /* 1-查看 */
    celCustomer(row) {
      this.openCel = true;
      this.form = { ...row };
    },
    handleCheck() {
      let params = { id: this.form.id };
      jrfkFxyjPus(params).then((res) => {
        if (res.status) {
          this.openCel = false;
          this.onLoad();
          this.getWebSocketDataList();
          this.initWebSocket();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    initWebSocket() {
      // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https   key你自定义的key
      //var host = window.location.host  m418160z45.mdo.co:18584
      //let websockUrl="ws://192.168.2.25:9002/jrfk/qyxx/api/websocket/"
      let websockUrl = process.env.VUE_APP_WEB_SOCKET_HOST;
      this.websock = new WebSocket(websockUrl + this.token);
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onmessage = this.websocketmessage;
      this.websock.onclose = this.websocketclose;
      //this.websock.send("您好啊");
    },
    websocketonopen() {
      console.log("wssuccess");
    },
    websocketonerror() {
      console.log("wsfail");
    },
    //这个是收到后端主动推送的值
    websocketmessage(e) {
      let dataList = JSON.parse(e.data);
      this.websocketonmessage(dataList);
    },
  },
};
</script>

<style scoped="scoped" lang="scss">
.el-row {
  margin-left: -6px !important;
}
/deep/ .el-descriptions-item__label.is-bordered-label {
  width: 120px !important;
}
.formBox {
  display: flex;
  padding: 0 10px;
}
.contBox {
  margin: 0 70px !important;
}
.spanClass:before {
  content: "";
  width: 20px;
  height: 20px;
  border: 3px solid #47a1ff;
  margin-right: 5px;
}
.spanClass {
  font-size: 17px;
  font-weight: 800;
}
.labelClassBox {
  position: relative;
  .labelClass {
    position: absolute;
    width: 10px;
    height: 10px;
    border-radius: 100%;
    background: red;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  }
}
// .setingBtn {
//   position: absolute;
//   top: 75px;
//   left: 300px;
//   color: #409eff;
//   font-size: 18px;
//   cursor: pointer;
// }
/* ::v-deep .el-tabs__nav-wrap::after {
  height: 0px;
} */
/deep/ .avue-crud__pagination {
  text-align: center;
}
.el-form-item {
  margin-bottom: 10px !important;
}
.chart-container {
  display: flex;
  margin-left: 20px;
}
#el-tab-pane {
  font-size: 40px;
  font-weight: bold;
}
.dialog-footer {
  text-align: center;
  margin: 20px auto;
}
.dialog-footerTwo {
  text-align: center;
}
.detailtable {
  width: 100%;
  border-collapse: collapse;
  border-spacing: 0;
  border: #e5e5e5 solid 1px;
}
.detailtable tr {
  width: 100%;
}
.detailtable td {
  padding: 8px 10px;
  text-align: left;
  line-height: 24px;
  font-size: 14px;
  color: #434343;
  border: #e5e5e5 solid 1px;
}
.detailtable td {
  font-weight: normal;
  background-color: #fff;
}
.detailtable td {
  word-break: break-all;
}
/deep/ .row {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-textarea {
  width: 100%;
}
</style>
